// 完工/竣工
import Taro from "@tarojs/taro";
import { View } from "@tarojs/components";
import pick from "lodash-es/pick";
import { useSet } from "ahooks";

import ByCol from "@/components/ui/ByCol";
import ByRow from "@/components/ui/ByRow";

import Card from "@/components/common/Card";
import ByCell from "@/components/ui/ByCell";
import ListView from "@/components/app/ListView";
import ByCheckbox from "@/components/ui/ByCheckbox";

import ApiFinance from "@/api/finance";
import useFetch from "@/hooks/useFetch";
import { objectToQueryString } from "@/utils";
import ByButton from "@/components/ui/ByButton";

/**
 * 工人卡片
 */

const WorkerCard = ({
  source,
  checked,
  onClick,
}: {
  source: any;
  checked: boolean;
  onClick: () => void;
}) => {
  return (
    <ByRow align="center" onClick={onClick}>
      <ByCol span={"none"} className="mr-2">
        <ByCheckbox checked={checked} />
      </ByCol>
      <ByCol span={"auto"}>
        <Card>
          <View>{source.workerName}</View>

          <ByRow content="between">
            <ByCell size="small" label="施工阶段：">
              {source.constructionProjectName}
            </ByCell>
            <ByCell size="small" label="工种：">
              {source.workerType}
            </ByCell>
          </ByRow>
        </Card>
      </ByCol>
    </ByRow>
  );
};

const formatList = (data: any[]): any[] => {
  return data
    ?.map(({ workers, ...rest }) => {
      return workers?.map((worker) => ({ ...worker, ...rest })) || [];
    })
    .flat(2);
};

export default ({
  active,
  intentCustomerId,
}: {
  active: 2 | 3;
  intentCustomerId: number;
}) => {
  const { data } = useFetch<any>(ApiFinance.getPayrollApplyList, {
    defaultParams: [{ intentCustomerId }],
    onAfter: ({ completionList, finalList }) => {
      return {
        finalList: formatList(finalList),
        completionList: formatList(completionList),
      };
    },
  });

  const { completionList = [], finalList = [] } = data || {};
  const [selected, { add, remove }] = useSet<any>();

  // 去申请
  const toApply = () => {
    const query = objectToQueryString({
      constructionProjectName: active == 2 ? "完工" : "竣工",
      intentCustomerId,
    });

    Taro.navigateTo({
      url: `apply?${query}`,
      success(res) {
        const map = new Map();

        [...selected].forEach((worker) => {
          const { workerType } = worker;
          let target = map.get(workerType);

          if (!target) {
            map.set(
              workerType,
              (target = {
                files: [],
                workerType,
                workerPayItems: [],
              })
            );
          }
          target.workerPayItems.push(pick(worker, ["workerId", "workerName"]));
        });

        res.eventChannel.emit("acceptWorkers", [...map.values()]);
      },
    });
  };

  const list = active == 2 ? completionList : finalList;

  return (
    <>
      <ListView isEmpty={list.length === 0}>
        {list?.map((item) => (
          <WorkerCard
            source={item}
            key={item.workerId}
            checked={selected.has(item)}
            onClick={() => (selected.has(item) ? remove(item) : add(item))}
          />
        ))}
      </ListView>
      {list.length > 0 && (
        <View className="mt-3 text-center">
          <ByButton inlineBlock disabled={selected.size == 0} onClick={toApply}>
            申请
          </ByButton>
        </View>
      )}
    </>
  );
};
